package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import model.Biologist;
import model.Family;
import model.Genus;
import model.Specie;

import org.jfree.ui.RefineryUtilities;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import control.CConnection;
import control.CFamily;
import control.CGenus;
import control.CSpecies;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FamilyAnalytics extends javax.swing.JFrame {
	private JLabel lblTitle;
	private JTextField txtInfo;
	private JButton bttSpeciesByGenus;
	private JButton bttSpeciesByFamily;
	private JButton bttGenusByFamily;
	private JPanel pnlAnalytics;
	private JButton bttStartExtraction;
	private JPanel pnlExtract;

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				FamilyAnalytics inst = new FamilyAnalytics();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public FamilyAnalytics() 
	{
		super();
		initGUI();
		txtInfo.setText("Ready for extract data from http://reptile-database.reptarium.cz");
		
		bttGenusByFamily.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				AnalyticGenusDataByFamily analytics = new AnalyticGenusDataByFamily("Genus by Family - Pie Chart");
		    	analytics.pack();
		        RefineryUtilities.centerFrameOnScreen(analytics);
		        analytics.setVisible(true);
			}
		});
		
		bttSpeciesByFamily.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				AnalyticSpeciesDataByFamily analytics = new AnalyticSpeciesDataByFamily("Species by Family - Pie Chart");
		    	analytics.pack();
		        RefineryUtilities.centerFrameOnScreen(analytics);
		        analytics.setVisible(true);
			}
		});
		
		bttSpeciesByGenus.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				AnalyticSpeciesDataByGenus analytics = new AnalyticSpeciesDataByGenus("Species by Genus - Pie Chart");
		    	analytics.pack();
		        RefineryUtilities.centerFrameOnScreen(analytics);
		        analytics.setVisible(true);
			}
		});
		
		bttStartExtraction.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) 
			{
				txtInfo.setText("Extracting data from http://reptile-database.reptarium.cz ...");
				extractData();
				txtInfo.setText("Data successfully extracted.");
			}
		});
	}
	
	private void extractData()
	{

		CConnection cn = new CConnection();
		
		Biologist biolgist = new Biologist();
		biolgist.setPass_number("1631230");
		
		Document doc;
		try 
		{
			cn.createConnection();
			CFamily cFamily = new CFamily(cn);
			CGenus cGenus = new CGenus(cn);
			CSpecies cSpecie = new CSpecies(cn);
			
			doc = Jsoup.connect("http://reptile-database.reptarium.cz/advanced_search?taxon=snake&location=Brazil&submit=Search").timeout(60000).get();
			Elements species = doc.select("#content ul li a");
			
			for (Element specieElement : species) 
			{
				String linkHref = specieElement.attr("href");
				Document snakePage = Jsoup.connect("http://reptile-database.reptarium.cz"+linkHref).timeout(60000).get();
				Elements data = snakePage.select("table.species td");
				
				Family family = new Family();
				family.setName(data.get(1).text().split(",")[0]);
				family.setDescription(data.get(1).text().split(",")[0]);
				
				try
				{
					cFamily.create(family);
				}
				catch (SQLIntegrityConstraintViolationException e) 
				{
					txtInfo.setText("duplicated family");
					System.out.println("duplicated family");
				}
				
				Genus genus = new Genus();
				genus.setFamily(family);
				genus.setName(specieElement.text().split(" ")[0]);
				genus.setDescription(specieElement.text().split(" ")[0]);
				
				try
				{
					cGenus.create(genus);
				}
				catch (SQLIntegrityConstraintViolationException e) 
				{
					txtInfo.setText("duplicated genus");
					System.out.println("duplicated genus");
				}
				
				
				Specie specie = new Specie();
				specie.setScientificName(specieElement.text().split(" ")[0]+" "+specieElement.text().split(" ")[1]);
				String usualName = data.get(5).text()==null?"empty":(data.get(5).text().length()>50?data.get(5).text().substring(0,50):data.get(5).text());
				specie.setUsualName(usualName.replaceAll("'", ""));
				String obs = data.get(13).text()==null?"empty":(data.get(13).text().length()>500?data.get(13).text().substring(0,500):data.get(13).text());
				specie.setObservations(obs.replaceAll("'", ""));
				specie.setBiologist(biolgist);
				specie.setGenus(genus);
				
				try{
					cSpecie.create(specie);
				}
				catch (SQLIntegrityConstraintViolationException e) 
				{
					txtInfo.setText("duplicated specie");
					System.out.println("duplicated specie");
				}
				
				
				txtInfo.setText("added "+specie.getScientificName() +" - "+specie.getUsualName());
				
			}
			
			
		} catch (IOException e) 
		{
			txtInfo.setText("Error extracting data: "+e.getLocalizedMessage());
			e.printStackTrace();
		} catch (SQLException e) 
		{
			txtInfo.setText("Error extracting data: "+e.getLocalizedMessage());
			e.printStackTrace();
		} catch (ClassNotFoundException e) 
		{
			txtInfo.setText("Error extracting data: "+e.getLocalizedMessage());
			e.printStackTrace();
		}
		
	
	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
			{
				lblTitle = new JLabel();
				getContentPane().add(lblTitle);
				lblTitle.setText("Families, Genus and Species Extract and Analytics");
				lblTitle.setBounds(12, 12, 476, 30);
				lblTitle.setFont(new java.awt.Font("Segoe UI",0,20));
				lblTitle.setHorizontalTextPosition(SwingConstants.CENTER);
				lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
			}
			{
				pnlExtract = new JPanel();
				getContentPane().add(pnlExtract);
				pnlExtract.setBounds(12, 48, 476, 142);
				pnlExtract.setBorder(BorderFactory.createTitledBorder("Extract"));
				pnlExtract.setLayout(null);
				{
					bttStartExtraction = new JButton();
					pnlExtract.add(bttStartExtraction);
					bttStartExtraction.setText("Start Extraction");
					bttStartExtraction.setBounds(17, 38, 443, 28);
				}
				{
					txtInfo = new JTextField();
					pnlExtract.add(txtInfo);
					txtInfo.setBounds(17, 87, 442, 28);
					txtInfo.setEditable(false);
				}
			}
			{
				pnlAnalytics = new JPanel();
				getContentPane().add(pnlAnalytics);
				pnlAnalytics.setBounds(12, 202, 476, 191);
				pnlAnalytics.setBorder(BorderFactory.createTitledBorder("Analytics"));
				pnlAnalytics.setLayout(null);
				{
					bttGenusByFamily = new JButton();
					pnlAnalytics.add(bttGenusByFamily);
					bttGenusByFamily.setText("Genus by Family Pie Chart");
					bttGenusByFamily.setBounds(139, 38, 194, 28);
				}
				{
					bttSpeciesByFamily = new JButton();
					pnlAnalytics.add(bttSpeciesByFamily);
					bttSpeciesByFamily.setText("Species By Family Pie Chart");
					bttSpeciesByFamily.setBounds(139, 82, 194, 28);
				}
				{
					bttSpeciesByGenus = new JButton();
					pnlAnalytics.add(bttSpeciesByGenus);
					bttSpeciesByGenus.setText("Species by Genus Pie Chart");
					bttSpeciesByGenus.setBounds(139, 127, 194, 28);
				}
			}
			pack();
			this.setSize(518, 450);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}

}
